<?php

namespace MemFrameWork;

use \Redis;

/**
 * memredis short summary.
 *
 * redis操作类
 *
 * @version 1.0
 * @author 张云江
 */
class MemRedis extends Mem
{
    /**
     * redis对象
     * @var Redis
     */
    private $redis;
    /**
     * 构建redis对象
     * @param array $viewrelatkey 关联对象
     * @param string $dbname 数据库名
     * @param string $tablename 数据表名
     */
    public function __construct($viewrelatkey, $dbname, $tablename)
    {
        parent::__construct($viewrelatkey, $dbname, $tablename);
        $this->init();
    }
    private function init()
    {
        if (!class_exists("Redis"))
            return;
        $config = \Config\RedisConfig::getConfig("global");
        if ($config) {
            $this->redis = new Redis();
            $iscon = $this->redis->connect($config["host"], $config["port"]);
            if (!$iscon)
                $this->redis = null;
        }
    }

    protected function clean($nkey)
    {
        if ($this->isEmptyWithConfig())
            return null;
        $keyarray = $this->redis->keys($nkey);
        $this->redis->del($keyarray);
        return $keyarray;
    }
    /**
     * 关闭redis
     */
    public function close()
    {
        if ($this->isEmptyWithConfig())
            return;
        $this->redis->close();
    }
    /**
     * 是否配置
     * @return bool
     */
    public function isEmptyWithConfig()
    {
        return $this->redis ? false : true;
    }

    #region Mem Members

    /**
     * 添加进缓存
     *
     * @param string $key 
     * @param array $array 
     */
    function set($key, $array)
    {
        if ($this->isEmptyWithConfig())
            return;
        $arraystr = json_encode($array);
        $key = $this->getKey($key);
        $this->redis->set($key, $arraystr);
    }

    /**
     * 获取数据的逻辑
     *
     * @param string $key 键名
     *
     * @return array
     */
    function get($key)
    {
        if ($this->isEmptyWithConfig())
            return null;
        $this->transDel();
        $key = $this->getKey($key);
        $arraystr = $this->redis->get($key);
        return json_decode($arraystr, true);
    }

    /**
     * 刷新缓存
     */
    function flush()
    {
        if ($this->isEmptyWithConfig())
            return;
        $this->redis->flushAll();
    }

    #endregion
}
